Imports org.model.lib.db

''' <summary>
''' Candidate code: Country COde/Lesson Code/Period Code/Student Counter for Country Code
''' </summary>
Public Class PVAKCandidateCodeGenerator
    Inherits ICandidateCodeGenerator

    Public Overrides Function getExistingCandidateCode() As String

        ' if the student exists already we keep the code
        Dim oldrecords As List(Of ClassMember) = ClassMemberDataUtils.findList("studentId={0}", _
                                     Me.student.StudentId)

        For Each cm As ClassMember In oldrecords
            If cm.PeriodClass.Period.DiplomaSuperTypeId = EnumDiplomaSuperTypes.PVAK AndAlso _
                    cm.PeriodClass.Lesson.LessonCode = Me.periodClass.Lesson.LessonCode Then

                Return cm.CandidateCode

            End If
        Next

        Return String.Empty

    End Function

    Public Overrides Function getStudentCounter() As Integer

        Dim sql = <sql>
select max(convert(int, right([CandidateCode],3))) from [vClassMember]
where DiplomaSuperTypeid=1 and CandidateCode like '%' + {0} + '%'
                  </sql>
        Dim ret As Integer = ModelContext.CurrentDBUtils.getLngValueWithParams(sql.Value, _
                                 "/" & Me.periodClass.Lesson.LessonCode & "/")
        ret = ret + 1

        Return ret

    End Function

    Public Overrides Function getNewCandidateCode() As String

        If Me.periodClass.ExamCenterID.GetValueOrDefault <= 0 Then
            Throw New ApplicationException( _
                String.Format("Please specify EXAM CENTER for period in order to generate the candidate code.  Exam Center not specified for Class {0}", _
                             Me.periodClass.ClassDescription))
        End If

        'Candidate code: Country Code/Lesson Code/Period Code/Student Counter for Country Code
        Dim candCode As String = Me.periodClass.ExamCenter.Country.CountryCode & "/" & _
                Me.periodClass.Lesson.LessonCode & "/" & _
                Me.periodClass.Period.PeriodCode & "/"

        Dim stCounter As Integer = Me.getStudentCounter

        candCode = candCode & Format(stCounter, "000")
        Return candCode

    End Function
End Class